package com.xiaoxin.nmzp.server.controller;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.xiaoxin.nmzp.server.entity.domain.SysUser;
import com.xiaoxin.nmzp.server.entity.req.UpdateUserReq;
import com.xiaoxin.nmzp.server.service.SysUserService;
import com.xiaoxin.nmzp.utils.JwtUtil;
import com.xiaoxin.nmzp.utils.UserUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


@RestController()
@RequestMapping("/nmzp/user")
public class UserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping
    public AjaxResult getLoginUser(){
        SysUser sysUser = UserUtils.get();
        return AjaxResult.success(sysUser);
    }

    @PutMapping("/update")
    public AjaxResult updateUser(@RequestBody UpdateUserReq updateUserReq){
        sysUserService.updateUser(updateUserReq);
        return AjaxResult.success();
    }

    @PostMapping("/avatar")
    public AjaxResult avatarUpload(MultipartFile file) throws Exception{
        if (!file.isEmpty()) {
            SysUser sysUser = UserUtils.get();
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            if (sysUserService.updateUserAvatar(sysUser.getUserName(), avatar)) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                sysUser.setAvatar(avatar);
                LoginUser loginUser = genLoginUser(sysUser);
                jwtUtil.setLoginUser(loginUser);
                return ajax;
            }
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    /**
     * 生成登录用户信息
     * @param sysUser
     * @return
     */
    private LoginUser genLoginUser(SysUser sysUser) {
        LoginUser loginUser = new LoginUser();
        com.ruoyi.common.core.domain.entity.SysUser user = new com.ruoyi.common.core.domain.entity.SysUser();
        BeanUtils.copyProperties(sysUser, user);
        loginUser.setUser(user);
        return loginUser;
    }

}
